import 'package:flutter/material.dart';

class ComponentCorrespondence extends StatefulWidget {
  @override
  _ComponentCorrespondenceState createState() =>
      _ComponentCorrespondenceState();
}

class _ComponentCorrespondenceState extends State<ComponentCorrespondence> {
  int count = 0;
  void addCount([String flag = '']) {
    // 接收子组件传递过来的值
    if (flag != '') {
      print('我是Counter子组件 传递过来的参数$flag');
    }
    setState(() {
      count += 1;
    }); //state中
    print('$count');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('父子组件通信$count'),
      ),
      // 父组件向子组件传值，及回调
      body: Counter(count: count, addCount: addCount),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => addCount(),
      ),
    );
  }
}

class Counter extends StatelessWidget {
  final int count;
  final addCount;

  // 子组件接收
  Counter({Key key, this.count, this.addCount}) : super(key: key); //构造
  @override
  Widget build(BuildContext context) {
    return Center(
      child: ActionChip(
        label: Text('$count'),
        onPressed: _addCount,
      ),
    );
  }

// 子组件调用父组件传递过来的方法，并传值给父组件
  void _addCount() {
    addCount('child');
  }
}
